package com.css.fxfzfxqh.modules.vulnerabilityData.cztDataMange.service.impl;

import cn.hutool.core.io.FileUtil;
import com.css.fxfzfxqh.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzfxqh.base.attachment.service.AttachmentInfoService;
import com.css.fxfzfxqh.base.response.RestResponse;
import com.css.fxfzfxqh.constants.YNEnum;
import com.css.fxfzfxqh.modules.vulnerabilityData.cztDataMange.entity.CphDamageEntity;
import com.css.fxfzfxqh.modules.vulnerabilityData.cztDataMange.entity.GstInformationEntity;
import com.css.fxfzfxqh.modules.vulnerabilityData.cztDataMange.entity.RdInformationEntity;
import com.css.fxfzfxqh.modules.vulnerabilityData.cztDataMange.exception.ShpFieldException;
import com.css.fxfzfxqh.modules.vulnerabilityData.cztDataMange.repository.DomeFacilitiesRepository;
import com.css.fxfzfxqh.modules.vulnerabilityData.cztDataMange.service.DomeFacilitiesService;
import com.css.fxfzfxqh.util.ParsingResult;
import com.css.fxfzfxqh.util.PlatformDateUtils;
import com.css.fxfzfxqh.util.ShpAnalyticUtil;
import com.css.fxfzfxqh.util.UUIDGenerator;
import com.css.fxfzfxqh.web.PlatformSessionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class DomeFacilitiesServiceImpl implements DomeFacilitiesService {

    @Autowired
    private DomeFacilitiesRepository domeFacilitiesRepository;

    @Autowired
    private AttachmentInfoService attachmentInfoService;

    @Value("${image.localDir}")
    private String localDir;

    @Override
    public RestResponse parseShp(String fileIds, String typeCode) {
        this.uniformFileName(fileIds);
        ParsingResult shpData = getShpData(fileIds);
        //是否成功
        if (!shpData.getMessage().equals("ok")) {
            return RestResponse.fail(shpData.getMessage());
        }
        RestResponse restResponse = null;
        if (typeCode.equals("1")) {
            try {
                restResponse = this.saveHpInformation(shpData);
                return restResponse;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return RestResponse.fail("该数据类别下没有shp数据");
            }
        }
        if (typeCode.equals("2")) {
            try {
                restResponse = this.saveGstInformation(shpData);
                return restResponse;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return RestResponse.fail("该数据类别下没有shp数据");
            }
        }
        if (typeCode.equals("3")) {
            try {
                restResponse = this.saveRdInformation(shpData);
                return restResponse;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return RestResponse.fail("该数据类别下没有shp数据");
            }
        }
        return restResponse;
    }

    private RestResponse saveRdInformation(ParsingResult shpData) {
        try {
            List<RdInformationEntity> list = getRdInformationList(shpData.getShpList());
            if (list == null) {
                return RestResponse.fail("字段数量不符合要求");
            }
            for (RdInformationEntity rdInformationEntity : list) {
                domeFacilitiesRepository.saveRdInformation(rdInformationEntity);
            }
            return RestResponse.succeed();
        } catch (Exception e1) {
            log.error(e1.getMessage(), e1);
            return RestResponse.fail("字段数量不符合要求");
        }
    }

    private List<RdInformationEntity> getRdInformationList(List<List<Object>> shpList) throws ShpFieldException, com.css.fxfzfxqh.exceptions.ShpFieldException {
        ArrayList<RdInformationEntity> arrayList = new ArrayList<>();
        for (int i = 0; i < shpList.size(); i++) {
            List<Object> list = shpList.get(i);
            if (list.size() != 18) {
                return null;
            }
            RdInformationEntity rd = new RdInformationEntity();
            rd.setCreateUser(PlatformSessionContext.getUserID());
            rd.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            rd.setDelFlag(YNEnum.N.toString());
            rd.setUploadTime(new Date());
            rd.setCrId(UUIDGenerator.getUUID());
            rd.setGeom(list.get(0).toString());
            rd.setCrName(ShpAnalyticUtil.getStringVal(list.get(1).toString(), "水坝名称", true));
            rd.setLocation(ShpAnalyticUtil.getStringVal(list.get(2).toString(), "水坝地点", false));
            rd.setLongitude(ShpAnalyticUtil.getStringVal(list.get(3).toString(), "经度", true));
            rd.setLatitude(ShpAnalyticUtil.getStringVal(list.get(4).toString(), "纬度", true));
            rd.setCapacity(ShpAnalyticUtil.getDoubleVal(list.get(5).toString(), "库容（立方米）", true));
            rd.setYear(ShpAnalyticUtil.getStringVal(list.get(6).toString(), "建造年代", true));
            rd.setDamLength(ShpAnalyticUtil.getDoubleVal(list.get(7).toString(), "坝长（米）", true));
            rd.setDamHeight(ShpAnalyticUtil.getDoubleVal(list.get(8).toString(), "坝高（米）", true));
            rd.setTopWidth(ShpAnalyticUtil.getDoubleVal(list.get(9).toString(), "顶宽（米）", true));
            rd.setStructureType(ShpAnalyticUtil.getStringVal(list.get(10).toString(), "结构类型", true));
            rd.setType(ShpAnalyticUtil.getStringVal(list.get(11).toString(), "水坝类型", true));
            rd.setIntensity(ShpAnalyticUtil.getStringVal(list.get(12).toString(), "设防烈度", true));
            rd.setSite(ShpAnalyticUtil.getStringVal(list.get(13).toString(), "位  置", true));
            rd.setSpace(ShpAnalyticUtil.getStringVal(list.get(14).toString(), "场  地", true));
            rd.setFilling(ShpAnalyticUtil.getStringVal(list.get(15).toString(), "填料", true));
            rd.setDamFoundation(ShpAnalyticUtil.getStringVal(list.get(16).toString(), "坝基", true));
            rd.setMaintenanceStatus(ShpAnalyticUtil.getStringVal(list.get(17).toString(), "维护现状", true));
        }
        return arrayList;
    }

    private RestResponse saveGstInformation(ParsingResult shpData) {
        try {
            List<GstInformationEntity> list = getGstInformationList(shpData.getShpList());
            if (list == null) {
                return RestResponse.fail("字段数量不符合要求");
            }
            for (GstInformationEntity gstInformationEntity : list) {
                domeFacilitiesRepository.saveGstInformation(gstInformationEntity);
            }
            return RestResponse.succeed();
        } catch (Exception e1) {
            log.error(e1.getMessage(), e1);
            return RestResponse.fail("字段数量不符合要求");
        }
    }

    private List<GstInformationEntity> getGstInformationList(List<List<Object>> shpList) throws ShpFieldException, com.css.fxfzfxqh.exceptions.ShpFieldException {
        ArrayList<GstInformationEntity> arrayList = new ArrayList<>();
        for (int i = 0; i < shpList.size(); i++) {
            List<Object> list = shpList.get(i);
            if (list.size() != 32) {
                return null;
            }
            GstInformationEntity gst = new GstInformationEntity();
            gst.setCreateUser(PlatformSessionContext.getUserID());
            gst.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            gst.setDelFlag(YNEnum.N.toString());
            gst.setUploadTime(new Date());
            gst.setCarId(UUIDGenerator.getUUID());
            gst.setGeom(list.get(0).toString());
            gst.setCarCode(ShpAnalyticUtil.getStringVal(list.get(1).toString(), "储气罐编码", false));
            gst.setCarName(ShpAnalyticUtil.getStringVal(list.get(2).toString(), "储气罐名称", true));
            gst.setLongitude(ShpAnalyticUtil.getStringVal(list.get(3).toString(), "经度", true));
            gst.setLatitude(ShpAnalyticUtil.getStringVal(list.get(4).toString(), "纬度", true));
            gst.setStyle(ShpAnalyticUtil.getStringVal(list.get(5).toString(), "型号", true));
            gst.setCapacity(ShpAnalyticUtil.getDoubleVal(list.get(6).toString(), "公称容积", true));
            gst.setPressure(ShpAnalyticUtil.getDoubleVal(list.get(7).toString(), "工作压力", true));
            gst.setInnerDiameter(ShpAnalyticUtil.getDoubleVal(list.get(8).toString(), "筒体内径", true));
            gst.setHeight(ShpAnalyticUtil.getDoubleVal(list.get(9).toString(), "筒体高度", true));
            gst.setThickness(ShpAnalyticUtil.getDoubleVal(list.get(10).toString(), "筒体、封头壁厚", true));
            gst.setWeight(ShpAnalyticUtil.getDoubleVal(list.get(11).toString(), "参考重量", true));
            gst.setMaterial(ShpAnalyticUtil.getStringVal(list.get(12).toString(), "结构材料", true));
            gst.setRailLength(ShpAnalyticUtil.getDoubleVal(list.get(13).toString(), "导轨长度", true));
            gst.setRailHeight(ShpAnalyticUtil.getDoubleVal(list.get(14).toString(), "导轨高度", true));
            gst.setRailThickness(ShpAnalyticUtil.getDoubleVal(list.get(15).toString(), "导轨中腹厚度", true));
            gst.setBaseType(ShpAnalyticUtil.getStringVal(list.get(16).toString(), "基础形式", true));
            gst.setMaterialType(ShpAnalyticUtil.getStringVal(list.get(17).toString(), "材料型号", false));
            gst.setElasticModulus(ShpAnalyticUtil.getDoubleVal(list.get(18).toString(), "弹性模量", false));
            gst.setYieldStress(ShpAnalyticUtil.getDoubleVal(list.get(19).toString(), "屈服应力", false));
            gst.setPermissibleStress(ShpAnalyticUtil.getDoubleVal(list.get(20).toString(), "许用应力", false));
            gst.setSite(ShpAnalyticUtil.getStringVal(list.get(21).toString(), "场地类别", false));
            gst.setLiquefaction6(ShpAnalyticUtil.getStringVal(list.get(22).toString(), "6度时液化程度", false));
            gst.setLiquefaction7(ShpAnalyticUtil.getStringVal(list.get(23).toString(), "7度时液化程度", false));
            gst.setLiquefaction8(ShpAnalyticUtil.getStringVal(list.get(24).toString(), "8度时液化程度", false));
            gst.setLiquefaction9(ShpAnalyticUtil.getStringVal(list.get(25).toString(), "9度时液化程度", false));
            gst.setSeismicSubsidence6(ShpAnalyticUtil.getStringVal(list.get(26).toString(), "6度时震陷程度", false));
            gst.setSeismicSubsidence7(ShpAnalyticUtil.getStringVal(list.get(27).toString(), "7度时震陷程度", false));
            gst.setSeismicSubsidence8(ShpAnalyticUtil.getStringVal(list.get(28).toString(), "8度时震陷程度", false));
            gst.setSeismicSubsidence9(ShpAnalyticUtil.getStringVal(list.get(29).toString(), "9度时震陷程度", false));
            gst.setYear(ShpAnalyticUtil.getIntegerVal(list.get(30).toString(), "建设年代", false));
            gst.setIntensity(ShpAnalyticUtil.getIntegerVal(list.get(31).toString(), "设防烈度", false));
        }
        return arrayList;
    }

    private RestResponse saveHpInformation(ParsingResult shpData) {
        try {
            List<CphDamageEntity> list = getHpInformationList(shpData.getShpList());
            if (list == null) {
                return RestResponse.fail("字段数量不符合要求");
            }
            for (CphDamageEntity cphDamageEntity : list) {
                domeFacilitiesRepository.saveHpInformation(cphDamageEntity);
            }
            return RestResponse.succeed();
        } catch (Exception e1) {
            log.error(e1.getMessage(), e1);
            return RestResponse.fail("字段数量不符合要求");
        }
    }

    private List<CphDamageEntity> getHpInformationList(List<List<Object>> shpList) throws ShpFieldException, com.css.fxfzfxqh.exceptions.ShpFieldException {
        ArrayList<CphDamageEntity> arrayList = new ArrayList<>();
        for (int i = 0; i < shpList.size(); i++) {
            List<Object> list = shpList.get(i);
            if (list.size() != 9) {
                return null;
            }
            CphDamageEntity cph = new CphDamageEntity();
            cph.setCreateUser(PlatformSessionContext.getUserID());
            cph.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            cph.setDelFlag(YNEnum.N.toString());
            cph.setUploadTime(new Date());
            cph.setCphdId(UUIDGenerator.getUUID());
            cph.setGeom(list.get(0).toString());
            cph.setSeismName(ShpAnalyticUtil.getStringVal(list.get(1).toString(), "地震名称", true));
            cph.setSeismTime(ShpAnalyticUtil.getTimeVal(list.get(2).toString(), "发生时间", true));
            cph.setMagnitude(ShpAnalyticUtil.getStringVal(list.get(3).toString(), "震级", true));
            cph.setProjectType(ShpAnalyticUtil.getStringVal(list.get(4).toString(), "重大工程类别", true));
            cph.setFortification(ShpAnalyticUtil.getStringVal(list.get(5).toString(), "设防情况", true));
            cph.setYears(ShpAnalyticUtil.getStringVal(list.get(6).toString(), "年代", true));
            cph.setParams(ShpAnalyticUtil.getDoubleVal(list.get(7).toString(), "地震动参数(烈度)", true));
            cph.setBreakState(ShpAnalyticUtil.getStringVal(list.get(8).toString(), "破坏状态", true));
        }
        return arrayList;
    }

    /**
     * 统一文件名
     *
     * @param fileIds
     */
    public void uniformFileName(String fileIds) {
        String[] idList = fileIds.split(",");
        AttachmentInfoEntity attachRoot = attachmentInfoService.getAttach(idList[0]);
        String attachRootPath = attachRoot.getAttachPath();
        String filePathCurrTime = getFilePathCurrTime(attachRootPath);
        for (int i = 1; i < idList.length; i++) {
            AttachmentInfoEntity attach = attachmentInfoService.getAttach(idList[i]);
            if (getFilePathCurrTime(attach.getAttachPath()).equals(filePathCurrTime)) {
                continue;
            }
            String attachPath = attach.getAttachPath();
            String fileDiskPath = localDir + attachPath;
            FileUtil.rename(new File(fileDiskPath), getNonSuffixFileName(attach.getAttachName()) + "_" + filePathCurrTime + "." + FileUtil.getSuffix(attach.getAttachName()), true);
            String[] s = attachPath.split("_");
            attach.setAttachPath(s[0] + "_" + filePathCurrTime + "." + FileUtil.getSuffix(attach.getAttachName()));
            attachmentInfoService.update(attach);
        }
    }

    private String getNonSuffixFileName(String fileName) {
        return fileName.replaceAll("." + FileUtil.getSuffix(fileName), "");
    }

    private String getFilePathCurrTime(String filePath) {
        return filePath.split("_")[1].replaceAll("." + FileUtil.getSuffix(filePath.split("_")[1]), "");
    }

    public ParsingResult getShpData(String fileIds) {
        //.prj结尾用来校验是否为2000坐标系
        String prj = "";
        //.cpg文件用来获得编码格式,例如utf-8
        String cpg = "";
        //.shp文件用来获得数据
        String shp = "";
        //根据id获取真实地址
        String[] split = fileIds.split(",");
        for (String id : split) {
            //根据id和文件名获取真实的放在磁盘上的文件
            AttachmentInfoEntity attachmentInfoEntity = attachmentInfoService.getAttach(id);
            String attachPath = attachmentInfoEntity.getAttachPath();
            String substring = attachPath.substring(attachPath.length() - 4);
            if (substring.equals(".prj")) {
                prj = localDir + File.separator + attachPath;
            } else if (substring.equals(".cpg")) {
                cpg = localDir + File.separator + attachPath;
            } else if (substring.equals(".shp")) {
                shp = localDir + File.separator + attachPath;
            }
        }
        return ShpAnalyticUtil.analytic(prj, cpg, shp);
    }

}
